package com.wens.ui.view

import android.content.Context
import android.graphics.Color
import android.graphics.PixelFormat.RGBA_8888
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.AttributeSet
import android.util.Log
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.ProgressBar
import androidx.annotation.RequiresApi
import com.google.android.material.color.MaterialColors
import com.wens.ui.R

class FullScreenProgressBar : FrameLayout {

    private var progressBar: View? = null

    var cancelable = false

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        init(context, attrs, defStyleAttr, 0)
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    constructor(
        context: Context,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int
    ) : super(context, attrs, defStyleAttr, defStyleRes) {
        init(context, attrs, defStyleAttr, defStyleRes)
    }

    constructor(context: Context, progressBar: View) : super(context) {
        this.progressBar = progressBar
        init(context, null, 0, 0)
    }

    private fun init(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) {
        if (childCount > 0) {
            progressBar = getChildAt(0)
        } else {
            if (progressBar == null) progressBar = ProgressBar(context)
            var layoutParams: LayoutParams? = progressBar!!.layoutParams as LayoutParams?
            if (layoutParams == null)
                layoutParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
            layoutParams.gravity = Gravity.CENTER
            progressBar!!.layoutParams = layoutParams
            addView(progressBar)
        }
        setOnClickListener { if (cancelable) dismiss() }

        val obtainStyledAttributes = context.obtainStyledAttributes(
            attrs,
            R.styleable.FullScreenProgressBar,
            defStyleAttr,
            defStyleRes
        )
        try {
            layoutParams?.width = obtainStyledAttributes.getLayoutDimension(
                R.styleable.FullScreenProgressBar_contentWidth,
                LayoutParams.WRAP_CONTENT
            )
            layoutParams?.height = obtainStyledAttributes.getLayoutDimension(
                R.styleable.FullScreenProgressBar_contentHeight,
                LayoutParams.WRAP_CONTENT
            )

            cancelable = obtainStyledAttributes.getBoolean(
                R.styleable.FullScreenProgressBar_cancelable,
                cancelable
            )
        } finally {
            obtainStyledAttributes.recycle()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        Log.i("JIE", "onKeyDown: ${javaClass.name}")
        return super.onKeyDown(keyCode, event)
    }

    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        Log.i("JIE", "dispatchKeyEvent: ${javaClass.name}")
        if (event?.keyCode == KeyEvent.KEYCODE_BACK) {
            if (cancelable) {
                dismiss()
                return true
            }
        }
        return super.dispatchKeyEvent(event)
    }

    fun show() {
        visibility = View.VISIBLE
    }

    fun dismiss() {
        if (fullScreenProgressBar == this)
            Companion.dismiss(context)
        else
            visibility = View.GONE
    }

    /**
     *  使用前必须初始化
     */
    companion object {
        private var fullScreenProgressBar: FullScreenProgressBar? = null

        fun init(context: Context) {
            init(context, null)
        }

        fun init(context: Context, progressDrawable: Drawable?) {
            if (fullScreenProgressBar == null) {
                if (progressDrawable != null) {
                    val progressBar = ImageView(context.applicationContext)
                    progressBar.layoutParams = LayoutParams(200, 200)
                    progressBar.setImageDrawable(progressDrawable)
                    fullScreenProgressBar =
                        FullScreenProgressBar(context.applicationContext, progressBar)
                } else {
                    fullScreenProgressBar = FullScreenProgressBar(context.applicationContext)
                }
                fullScreenProgressBar!!.setBackgroundColor(
                    MaterialColors.getColor(
                        context,
                        R.attr.progressBackgroundColor,
                        Color.parseColor("#80000000")
                    )
                )
            }
        }

        fun init(fullScreenProgressBar: FullScreenProgressBar) {
            if (Companion.fullScreenProgressBar == null)
                FullScreenProgressBar.fullScreenProgressBar = fullScreenProgressBar
        }

        fun show(context: Context, cancelable: Boolean = false) {
            if (fullScreenProgressBar == null) {
                throw RuntimeException("fullScreenProgressBar is not init,please call FullScreenProgressBar.init before call show")
            }
            if (fullScreenProgressBar!!.windowToken == null) {
                synchronized(fullScreenProgressBar!!) {
                    if (fullScreenProgressBar!!.windowToken == null) {
                        val windowManager: WindowManager? =
                            context.getSystemService(Context.WINDOW_SERVICE) as WindowManager?
                        val layoutParams = WindowManager.LayoutParams(
                            WindowManager.LayoutParams.MATCH_PARENT,
                            WindowManager.LayoutParams.MATCH_PARENT
                        )
                        layoutParams.type =
                            WindowManager.LayoutParams.TYPE_APPLICATION
                        layoutParams.flags =
                            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                        layoutParams.gravity = Gravity.CENTER
                        layoutParams.format = RGBA_8888
                        windowManager?.addView(fullScreenProgressBar, layoutParams)
                        fullScreenProgressBar!!.cancelable = cancelable
                    }
                }
            }
        }

        fun dismiss(context: Context) {
            if (fullScreenProgressBar == null) {
                throw RuntimeException("fullScreenProgressBar is not init,please call FullScreenProgressBar.init before call dismiss")
            }
            if (fullScreenProgressBar!!.windowToken != null) {
                synchronized(fullScreenProgressBar!!) {
                    if (fullScreenProgressBar!!.windowToken != null) {
                        val windowManager: WindowManager? =
                            context.getSystemService(Context.WINDOW_SERVICE) as WindowManager?
                        windowManager?.removeView(fullScreenProgressBar)
                    }
                }
            }
        }
    }
}

